package it.koutifaris.travianmap.communication.urlverifier;

import java.net.HttpURLConnection;
import java.net.URL;

public class UrlVerifierService {

	private static final String HEAD = "HEAD";
	private boolean followRedirect;

	public boolean verifyResourceExists(URL serverUrl) throws Exception {
		disableRedirect();

		HttpURLConnection huc = (HttpURLConnection) serverUrl.openConnection();
		huc.setRequestMethod(HEAD);
		boolean result = (huc.getResponseCode() == HttpURLConnection.HTTP_OK);
		huc.disconnect();

		restoreRedirect();

		return result;
	}

	private void disableRedirect() {
		followRedirect = HttpURLConnection.getFollowRedirects();
		HttpURLConnection.setFollowRedirects(false);
	}

	private void restoreRedirect() {
		HttpURLConnection.setFollowRedirects(followRedirect);
	}

}
